#include "Alarm.hpp"
#include "Clock.hpp"
#include "AssetManager.hpp"
#include "Notification.hpp"
#include "Util.hpp"
#include "Config.hpp"
#include <cpp3ds/System/I18n.hpp>
#include <cpp3ds/System/FileSystem.hpp>
#include <TweenEngine/Tween.h>
#include <time.h>
#include <stdlib.h>

namespace Clock {

Alarm::Alarm()
{
	float posY = 60.f;
	for (int i = 0; i < 5; ++i) {
		std::shared_ptr<AlarmItem> item(new AlarmItem(0, 0, false, i));
		m_alarmItems.emplace_back(std::move(item));
		AlarmItem *lastItemPointer = m_alarmItems.back().get();

		lastItemPointer->setPosition(120.f, posY);

		posY += 40.f;
	}
}

Alarm::~Alarm()
{

}

void Alarm::draw(cpp3ds::RenderTarget &target, cpp3ds::RenderStates states) const
{
	states.transform *= getTransform();

	for (auto& item : m_alarmItems) {
		target.draw(*item, states);
	}
}

void Alarm::update(float delta)
{
	m_tweenManager.update(delta);

	for (auto& item : m_alarmItems) {
		item->update(delta);
	}
}

void Alarm::processEvent(const cpp3ds::Event& event)
{
	for (auto& item : m_alarmItems) {
		item->processEvent(event);
	}
}

void Alarm::saveAlarms()
{
	rapidjson::Value array;
	array.SetArray();
	for (auto& item : m_alarmItems) {
		rapidjson::Value val;
		val.SetArray();

		val.PushBack(item->getAlarmHour(), Config::getAllocator());
		val.PushBack(item->getAlarmMinute(), Config::getAllocator());
		val.PushBack(item->isAlarmEnabled(), Config::getAllocator());

		array.PushBack(val, Config::getAllocator());
	}
	Config::set(Config::Alarms, array);
	Config::saveToFile();
}

void Alarm::loadAlarms()
{
	int i = 0;
	auto array = Config::get(Config::Alarms).GetArray();
	for (auto& item : m_alarmItems) {
		if (i + 1 > array.Capacity())
			break;

		auto val = array[i].GetArray();
		if (val.Capacity() >= 3) {
			item->setAlarmHour(val[0].GetInt() % 24);
			item->setAlarmMinute(val[1].GetInt() % 60);
			if (val[2].GetBool())
				item->enableAlarm();
		}

		i++;
	}
}

} // namespace Clock
